package com.flmes.base.service.impl;

import com.flmes.base.base.model.UserToken;
import com.flmes.base.config.FlmesConfig;
import com.flmes.base.constant.RequestConstant;
import com.flmes.base.model.domain.User;
import com.flmes.base.service.AuthService;
import com.flmes.base.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: flmes
 * @Date: 2024/10/8 20:34
 */
@Service
public class JwtService implements AuthService {

    private final SecretKey key;
    private final Integer expired;

    public JwtService(FlmesConfig config) {
        this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(config.getAuth().getSecret()));
        this.expired = config.getAuth().getExpired();
    }

    @Override
    public String getToken(User user) {
        Map<String, Object> params = new HashMap<>();
        params.put(RequestConstant.ID, user.getId());
        params.put(RequestConstant.USERNAME, user.getUsername());
        return JwtUtil.getJwt(key, params, expired);
    }

    @Override
    public UserToken getUserInfoByToken(String token) {
        Claims claims = JwtUtil.parseJwt(key, token);
        Integer id = claims.get(RequestConstant.ID, Integer.class);
        String username = claims.get(RequestConstant.USERNAME, String.class);
        if (Objects.isNull(id) || Objects.isNull(username)) {
            return null;
        }
        return new UserToken(id, username);
    }

}
